package com.cycle.community.controller;

import com.cycle.community.constant.CommentConstant;
import com.cycle.community.constant.CommunityConstant;
import com.cycle.community.entity.Comment;
import com.cycle.community.entity.DiscussPost;
import com.cycle.community.entity.Event;
import com.cycle.community.event.EventProducer;
import com.cycle.community.service.CommentService;
import com.cycle.community.service.DiscussPostService;
import com.cycle.community.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.Date;

/**
 * @author lenovo
 * @create 2022/8/15 0:12
 */
@Controller
@RequestMapping("/comment")
public class CommentController implements CommunityConstant {

    @Autowired
    private CommentService commentService;
    @Autowired
    private HostHolder hostHolder;//获取userId
    @Autowired
    private EventProducer eventProducer;
    @Autowired
    private DiscussPostService discussPostService;

    //要重定向回帖子里
    @RequestMapping(path = "/add/{discussPostId}", method = RequestMethod.POST)
    public String addComment(@PathVariable("discussPostId") long discussPostId, Comment comment) {
        //TODO 用户如果哦没登录就会报错，后面会统一处理
        comment.setUserId(hostHolder.getUser().getId());
        comment.setStatus(CommentConstant.VALID);
        comment.setCreateTime(new Date());
        commentService.addComment(comment);
        //触发评论事件
        Event event = new Event()
                .setTopic(TOPIC_COMMENT)
                .setUserId(hostHolder.getUser().getId())
                .setEntityType(comment.getEntityType())
                .setEntityId(comment.getEntityId())
                .setData("postId", discussPostId);//帖子id，可以链接到帖子，不是必要，所以存到map里
        //评论的目标可能是帖子，也可能是评论
        if (comment.getEntityType() == ENTITY_TYPE_POST) {
            //查帖子
            DiscussPost target = discussPostService.findDiscussPostById(comment.getEntityId());
            event.setEntityUserId(target.getUserId());
        } else if (comment.getEntityType() == ENTITY_TYPE_COMMENT) {
            Comment target = commentService.findCommentById(comment.getEntityId());
            event.setEntityUserId(target.getUserId());
        }
        eventProducer.fireEvent(event);//创建线程响应，异步处理，人多的话可以缓冲慢慢处理，不用担心性能问题
        //可以评论给帖子，也可以评论给回复
        if (comment.getEntityType() == ENTITY_TYPE_POST) {
            //触发发帖事件
            event = new Event()
                    .setTopic(TOPIC_PUBLISH)
                    .setUserId(comment.getUserId())
                    .setEntityType(ENTITY_TYPE_POST)
                    .setEntityId(discussPostId);
            eventProducer.fireEvent(event);
        }

        return "redirect:/discuss/detail/" + discussPostId;
    }


}
